const expres = require('express');
const router = expres.Router();
const { Like, Course, User } = require('../models');
const { BadRequestError } = require('../utils/errors');
const { successResponse, failureResponse } = require('../utils/responses');

router.post('/', async (req, res) => {
  try {
    const userId = req.userId
    const { courseId } = req.body
    const course = await Course.findByPk(courseId);
    if (!course) {
      throw new BadRequestError('课程不存在')
    }

    const like = await Like.findOne({ where: { userId, courseId } });
    if (!like) {
      await Like.create({ userId, courseId });
      await course.increment('likesCount');
      successResponse(res, '点赞成功');
    } else {
      await like.destroy()
      await course.decrement('likesCount');
      successResponse(res, '取消点赞成功');

    }
  } catch (error) {
    failureResponse(res, error);
  }
});

// 获取当前用户点赞的课程
router.get('/', async (req, res) => {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1
    const pageSize = Math.abs(Number(query.pageSize)) || 10
    const offset = (currentPage - 1) * pageSize;

    const user = await User.findByPk(req.userId);
    const courses = await user.getLikeCourses({
      joinTableAttributes: [], // 不查询关联表的数据
      attributes: { exclude: ['CategoryId', 'UserId', 'content'] },
      order: [['id', 'DESC']],
      limit: pageSize,
      offset: offset,
    });
    const count = await user.countLikeCourses();
    successResponse(res, '成功查询用户点赞的课程', {
      courses,
      pagination: {
        currentPage,
        pageSize,
        total: count,
      }
    });
  } catch (error) {
    failureResponse(res, error);
  }
});

module.exports = router;